﻿using System;
using System.Data;
using System.Linq;
using org.se.fs.presenter.ITask.Profile;
using org.se.fs.presenter.IView.Profile;
using org.se.fs.presenter.IView.Template;
using org.se.fs.presenter.Library;

namespace org.se.fs.presenter.View.Profile
{
    public class ClientInstitutionSubMenu : Template.SubMenu, ISubMenus
    {
        private readonly IClientInstitutionSubMenu _view;
        private readonly IClientInstitution _task;
        private readonly IInstitution _taskInstitution;
        private DataTable _institution;
        private UInt64 _clientId;

        public ClientInstitutionSubMenu(IClientInstitutionSubMenu view) : this(view, new Task.Context.ClientInstitution(), new Task.Context.Institution()) { }

        public ClientInstitutionSubMenu(IClientInstitutionSubMenu view, IClientInstitution task, IInstitution taskInstitution)
        {
            _view = view;
            _task = task;
            _taskInstitution = taskInstitution;
        }

        public void Initialize()
        {
            _task.OnDelete += TaskOnInsert;
            _task.OnFetch += TaskOnFetch;
            _task.OnFetchLists += TaskOnFetchLists;
            _task.OnInsert += TaskOnInsert;
            _task.OnToggle += TaskOnToggle;
            _task.OnUpdate += TaskOnUpdate;
            _taskInstitution.OnGetInstitutionActive+=TaskInstitutionOnGetInstitutionActive;

            _view.SetLabel(Data == null ? @"Create New Client Institution" : @"Modify Client Institution");
            _view.ButtonAddVisible(Data == null);
            _view.ButtonUpdateVisible(Data != null);

            if (Data != null)
                SetData();

            _taskInstitution.GetInstitutionActive();
        }

        //void TaskClientOnFetchLists(object source, FormEvent e)
        //{
        //    _client = (DataTable)e.Value;

        //    if (!e.IsSuccess)
        //        return;

        //    var a =
        //        (_client.AsEnumerable().Select(
        //            b =>
        //            String.Format("{0}, {1}, {2}", b.Field<string>("last_name"), b.Field<string>("first_name"),
        //                          b.Field<string>("middle_name").Substring(0, 1)))).ToArray();
        //    _view.FillClient(a);

        //    if (Data.Rows.Count.Equals(0))
        //        return;

        //    for (var i = 0; i < _client.Rows.Count; i++)
        //    {
        //        if (!_client.Rows[i]["id"].ToString().Equals(Data.Rows[0]["client_id"].ToString())) continue;
        //        _view.IndexClient = i;
        //        break;
        //    }
        //}

        void TaskInstitutionOnGetInstitutionActive(object source, FormEvent e)
        {
            _institution = (DataTable)e.Value;

            if (!e.IsSuccess)
                return;

            var a =
                (_institution.AsEnumerable().Select(
                    b => string.Format("{0}-{1}", b.Field<string>("name"), b.Field<string>("code")))).ToArray();
            _view.FillInstitution(a);

            if (Data == null)
                return;

            for (var i = 0; i < _institution.Rows.Count; i++)
            {
                if (!_institution.Rows[i]["id"].ToString().Equals(Data.Rows[0]["institution_id"].ToString())) continue;
                _view.IndexInstitution = i;
                break;
            }
        }

        public void TaskOnFetch(object source, FormEvent e)
        {
        }

        public void TaskOnFetchLists(object source, FormEvent e)
        {
        }

        public void TaskOnInsert(object source, FormEvent e)
        {
            _view.ButtonAddEnable(true);
            TriggerModify(new FormEvent(e.IsSuccess) { Exception = e.Exception, Value = e.Value });
        }

        public void TaskOnUpdate(object source, FormEvent e)
        {
            _view.ButtonUpdateEnable(true);
            TriggerModify(new FormEvent(e.IsSuccess) {Exception = e.Exception, Value = e.Value});
        }

        public void TaskOnDelete(object source, FormEvent e)
        {
        }

        public void TaskOnToggle(object source, FormEvent e)
        {
        }

        public void SetData()
        {
            if(Data.Rows.Count.Equals(0))
                return;

            _view.Department = Data.Rows[0]["department"].ToString();
            _view.Employed = Convert.ToBoolean(Data.Rows[0]["is_employed"].ToString());
            _view.Salary = Convert.ToDecimal(Data.Rows[0]["salary"].ToString());
            _view.Position = Data.Rows[0]["position"].ToString();
        }

        public void Add()
        {
            if (!Validate())
                return;

            _view.ButtonAddEnable(false);

            Data = new DataTable();
            Data.Columns.Add("id", typeof(UInt64));
            Data.Columns.Add("client_id", typeof(UInt64));
            Data.Columns.Add("institution_id", typeof(UInt64));
            Data.Columns.Add("department", typeof(string));
            Data.Columns.Add("is_employed", typeof(bool));
            Data.Columns.Add("salary", typeof(decimal));
            Data.Columns.Add("position", typeof(string));
            Data.Columns.Add("user_create_id", typeof(UInt64));
            Data.Columns.Add("created_date", typeof(DateTime));
            Data.Columns.Add("is_active", typeof(bool));

            var a = Data.NewRow();
            a["client_id"] = _clientId;
            a["institution_id"] = Convert.ToUInt64(_institution.Rows[_view.IndexInstitution]["id"].ToString());
            a["department"] = _view.Department;
            a["is_employed"] = _view.Employed;
            a["salary"] = _view.Salary;
            a["position"] = _view.Position;
            a["user_create_id"] = Convert.ToUInt64(Config.User.Rows[0]["id"].ToString());
          
            Data.Rows.Add(a);
            _task.Insert(Data);
        }

        public void Modify()
        {
            if(!Validate())
                return;

            _view.ButtonUpdateEnable(false);
            Data.Rows[0]["institution_id"] = Convert.ToUInt64(_institution.Rows[_view.IndexInstitution]["id"].ToString());
            Data.Rows[0]["department"] = _view.Department;
            Data.Rows[0]["is_employed"] = _view.Employed;
            Data.Rows[0]["salary"] = _view.Salary;
            Data.Rows[0]["position"] = _view.Position;
            Data.Rows[0]["user_create_id"] = Convert.ToUInt64(Config.User.Rows[0]["id"].ToString());
            _task.Update(Data);
        }

        public bool Validate()
        {
            if (_view.IndexInstitution.Equals(-1))
            {
                TriggerValidate(new FormEvent(false) { Exception = new Exception("Invalid empty institution.") });
                _view.FocusInstitution();
                return false;
            }

            if (string.IsNullOrEmpty(_view.Department.Trim()))
            {
                TriggerValidate(new FormEvent(false) { Exception = new Exception("Invalid empty department.") });
                _view.FocusDepartment();
                return false;
            }

            TriggerValidate(new FormEvent(true));
            return true;
        }

        public void SetClientId(UInt64 clientId)
        {
            _clientId = clientId;
        }
    }
}
